package com.navi168.fwq21.hyzl;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.location.Address;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.navi168.fwq21.hyzl.RouteSearchPoiDialog.OnListItemClick;
import com.navi168.fwq21.hyzl.mod.MypoiItems;
import com.navi168.fwq21.util.Constants;
import com.navi168.fwq21.util.SendPosition;
import com.amap.mapapi.core.AMapException;
import com.amap.mapapi.core.GeoPoint;
import com.amap.mapapi.core.PoiItem;
import com.amap.mapapi.geocoder.Geocoder;
import com.amap.mapapi.map.MapActivity;
import com.amap.mapapi.map.MapController;
import com.amap.mapapi.map.MapView;
import com.amap.mapapi.map.Overlay;
import com.amap.mapapi.map.RouteMessageHandler;
import com.amap.mapapi.map.RouteOverlay;
import com.amap.mapapi.poisearch.PoiPagedResult;
import com.amap.mapapi.poisearch.PoiSearch;
import com.amap.mapapi.poisearch.PoiTypeDef;
import com.amap.mapapi.poisearch.PoiSearch.Query;
import com.amap.mapapi.route.Route;
import com.navi168.fwq21.R;

public class Drive extends MapActivity implements RouteMessageHandler{
	
	private Button fromButton;
	private Button toButton;
	private Button okButton;
	private Button backButton;
	private Button changeButton;
	private AutoCompleteTextView fromEditText;
	private AutoCompleteTextView toEditText;
	private String midString;
	
	private MapView mMapView;
	private MapController mMapController;
	private GeoPoint point;
	
	private ProgressDialog progDialog;
	private PoiPagedResult startSearchResult;
	private PoiPagedResult endSearchResult;
	private String strStart;
	private String strEnd;
	private GeoPoint startPoint=null;
	private GeoPoint endPoint=null;
	private MapPointOverlay overlay;
	private String poiType;
	private List<Route> routeResult;
	private RouteOverlay ol;
	
	private String cityname;
	private String fromname;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.drive);
		Bundle bundle = this.getIntent().getExtras();
		fromname = bundle.getString("fromname");
	
		findViews();	
		setlisters();
		SharedPreferences settings = getSharedPreferences(Constants.SPF,
				MODE_WORLD_READABLE);
		cityname = settings.getString("city_now", "021");
		point = new GeoPoint(
				settings.getInt("city_lat", (int) (31.18334 * 1E6)),
				settings.getInt("city_long", (int) (121.43348 * 1E6)));
		mMapView.setBuiltInZoomControls(true);
		mMapController = mMapView.getController();
		mMapController.setCenter(point); // 设置地图中心点
		mMapController.setZoom(13);
		overlay=new MapPointOverlay(this);
		
	}
	


	private void setlisters() {
		fromButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showToast("在地图上点击您的起点");
				poiType="startPoint";
				mMapView.getOverlays().add(overlay);
			}
		});
		
		toButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showToast("在地图上点击您的终点");
				poiType="endPoint";
				mMapView.getOverlays().add(overlay);
			}
		});
		
		
		okButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				strStart = fromEditText.getText().toString().trim();
				strEnd = toEditText.getText().toString().trim();
				if (strStart==null||strStart.length()==0) {
					Toast.makeText(Drive.this, "请选择起点",
							Toast.LENGTH_SHORT).show();
					return;
				}
				if (strEnd==null||strEnd.length()==0) {
					Toast.makeText(Drive.this, "请选择终点",
							Toast.LENGTH_SHORT).show();
					return;
				}
				
				startSearchResult();
			}
		});
		
		backButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Drive.this.finish();
				
			}
		});
		
		changeButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				midString = fromEditText.getText().toString();
				fromEditText.setText(toEditText.getText().toString());
				toEditText.setText(midString);
				strStart = toEditText.getText().toString();
				strEnd = midString;
				if (strEnd.equals("地图上的点") || strStart.equals("地图上的点")) {
					GeoPoint geomid = new GeoPoint();
					geomid = startPoint;
					startPoint = endPoint;
					endPoint = geomid;
				}
			}
		});
		
	}


	private void findViews() {
		
		fromButton = (Button) findViewById(R.id.buttonform);
		toButton = (Button) findViewById(R.id.buttonto);
		changeButton = (Button) findViewById(R.id.change);
		okButton = (Button) findViewById(R.id.ok);
		backButton = (Button) findViewById(R.id.cance);
		fromEditText = (AutoCompleteTextView) findViewById(R.id.from);
		toEditText = (AutoCompleteTextView) findViewById(R.id.to);
		mMapView = (MapView) findViewById(R.id.route_MapView);
		fromEditText.setText(fromname);
		
	}
	
	
	// 查询路径规划起点
		public void startSearchResult() {
			strStart = fromEditText.getText().toString().trim();
			if(startPoint!=null&&strStart.equals("地图上的点")){
				endSearchResult();
			}else{
				final Query startQuery = new Query(strStart, PoiTypeDef.All, cityname);
				progDialog = ProgressDialog.show(Drive.this, null,
						"正在搜索您所需信息...", true, true);
				Thread t = new Thread(new Runnable() {
					@Override
					public void run() {
						// 调用搜索POI方法
						PoiSearch poiSearch = new PoiSearch(Drive.this, startQuery); // 设置搜索字符串
						try {
							startSearchResult = poiSearch.searchPOI();
							if(progDialog.isShowing()){
								routeHandler.sendMessage(Message.obtain(routeHandler,
										Constants.ROUTE_START_SEARCH));
						}
						} catch (AMapException e) {
							Message msg = new Message();
							msg.what = Constants.ROUTE_SEARCH_ERROR;
							msg.obj =  e.getErrorMessage();
							routeHandler.sendMessage(msg);
						} 
					}

				});
				t.start();
			}
		}
		
		// 查询路径规划终点
		public void endSearchResult() {
			
			strEnd = toEditText.getText().toString().trim();
			if(endPoint!=null&&strEnd.equals("地图上的点")){
				searchRouteResult(startPoint,endPoint);
			}else{
				final Query endQuery = new Query(strEnd, PoiTypeDef.All, cityname);
		        progDialog = ProgressDialog.show(Drive.this, null,
						"正在搜索您所需信息...", true, false);
				Thread t = new Thread(new Runnable() {
					@Override
					public void run() {
						PoiSearch poiSearch = new PoiSearch(Drive.this,endQuery); // 设置搜索字符串
						try {
							endSearchResult = poiSearch.searchPOI();
							if(progDialog.isShowing()){
							 routeHandler.sendMessage(Message.obtain(routeHandler,
									Constants.ROUTE_END_SEARCH));
							}
						} catch (AMapException e) {
							Message msg = new Message();
							msg.what = Constants.ROUTE_SEARCH_ERROR;
							msg.obj =  e.getErrorMessage();
							routeHandler.sendMessage(msg);
						} 
					}

				});
				t.start();
			}
		}
		
		
		public void searchRouteResult(GeoPoint startPoint, GeoPoint endPoint) {
			progDialog = ProgressDialog.show(Drive.this, null,
					"正在获取线路", true, true);
			final Route.FromAndTo fromAndTo = new Route.FromAndTo(startPoint,
					endPoint);
			Thread t = new Thread(new Runnable() {
				@Override
				public void run() {

					try {
						routeResult = Route.calculateRoute(Drive.this,
								fromAndTo, Route.DrivingDefault);
						if(progDialog.isShowing()){
							if(routeResult!=null||routeResult.size()>0)
							routeHandler.sendMessage(Message
									.obtain(routeHandler, Constants.ROUTE_SEARCH_RESULT));
						}
					} catch (AMapException e) {
						Message msg = new Message();
						msg.what = Constants.ROUTE_SEARCH_ERROR;
						msg.obj =  e.getErrorMessage();
						routeHandler.sendMessage(msg);
					}
				}
			});
			t.start();

		}
	
	
	
	private Handler routeHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == Constants.ROUTE_START_SEARCH) {
				progDialog.dismiss();
				try {
					List<PoiItem> poiItems;
					if (startSearchResult != null && (poiItems = startSearchResult.getPage(1)) != null 
							&& poiItems.size() > 0) {
						RouteSearchPoiDialog dialog = new RouteSearchPoiDialog(
								Drive.this, poiItems);

						dialog.setTitle("您要找的起点是:");
						dialog.show();
						dialog.setOnListClickListener(new OnListItemClick() {
							@Override
							public void onListItemClick(
									RouteSearchPoiDialog dialog,
									PoiItem startpoiItem) {
								startPoint = startpoiItem.getPoint();
								strStart = startpoiItem.getTitle();
								fromEditText.setText(strStart);
								endSearchResult();
							}

						});
					} else {
						showToast("无搜索起点结果,建议重新设定...");
					}
				} catch (AMapException e) {
					e.printStackTrace();
				}

			} else if (msg.what == Constants.ROUTE_END_SEARCH) {
				progDialog.dismiss();
				try {
					List<PoiItem> poiItems;
					if (endSearchResult != null && (poiItems = endSearchResult.getPage(1)) != null 
							&& poiItems.size() > 0) {
						RouteSearchPoiDialog dialog = new RouteSearchPoiDialog(
								Drive.this, poiItems);
						dialog.setTitle("您要找的终点是:");
						dialog.show();
						dialog.setOnListClickListener(new OnListItemClick() {
							@Override
							public void onListItemClick(
									RouteSearchPoiDialog dialog,
									PoiItem endpoiItem) {
								// TODO Auto-generated method stub
								endPoint = endpoiItem.getPoint();
								strEnd = endpoiItem.getTitle();
								toEditText.setText(strEnd);
								searchRouteResult(startPoint, endPoint);
							}

						});
					} else {
						showToast("无搜索起点结果,建议重新设定...");
					}
				} catch (AMapException e) {
					e.printStackTrace();
				}

			} else if (msg.what == Constants.ROUTE_SEARCH_RESULT) {
				progDialog.dismiss();
				if (routeResult != null && routeResult.size()>0) {
					Route route = routeResult.get(0);
					if (route != null) {
						if (ol != null) {
							ol.removeFromMap(mMapView);
						}
						ol = new RouteOverlay(Drive.this, route);
						ol.registerRouteMessage(Drive.this); // 注册消息处理函数
						ol.addToMap(mMapView); // 加入到地图
						ArrayList<GeoPoint> pts = new ArrayList<GeoPoint>();
						pts.add(route.getLowerLeftPoint());
						pts.add(route.getUpperRightPoint());
						mMapView.getController().setFitView(pts);//调整地图显示范围
						mMapView.invalidate();
					}
				}
			} else if (msg.what == Constants.ROUTE_SEARCH_ERROR) {
				progDialog.dismiss();
				showToast((String)msg.obj);
			}
		}
	};
	
	
	public class MapPointOverlay extends Overlay{
	    private Context context;
	    private LayoutInflater inflater;
	    private View popUpView;
	    public MapPointOverlay(Context context){
	    	this.context=context;
	    	inflater = (LayoutInflater)context.getSystemService(
	    	        Context.LAYOUT_INFLATER_SERVICE);
	    }
		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			// TODO Auto-generated method stub
			super.draw(canvas, mapView, shadow);                
		}

		@Override
		public boolean onTap(final GeoPoint point, final MapView view) {
			if(popUpView!=null){
				view.removeView(popUpView);
			}
		   // Projection接口用于屏幕像素点坐标系统和地球表面经纬度点坐标系统之间的变换
		    popUpView=inflater.inflate(R.layout.popup2, null);
			TextView textView=(TextView) popUpView.findViewById(R.id.PoiName);
			textView.setText("点击即可选择此点");
			MapView.LayoutParams lp;
			lp = new MapView.LayoutParams(MapView.LayoutParams.WRAP_CONTENT,
					MapView.LayoutParams.WRAP_CONTENT,
					point,0,0,
					MapView.LayoutParams.BOTTOM_CENTER);
				view.addView(popUpView,lp);
			popUpView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if(poiType.equals("startPoint")){
						fromEditText.setText("地图上的点");
						fromEditText.selectAll();
						startPoint = point;
					}
					
					if(poiType.equals("endPoint")){
						toEditText.setText("地图上的点");
						toEditText.selectAll();
						endPoint = point;
					}
					
					view.removeView(popUpView);
					view.getOverlays().remove(overlay);
				}
			});
	        return super.onTap(point, view);
		}
	}
	
	private void showToast(String showString) {
		Toast.makeText(getApplicationContext(), showString, Toast.LENGTH_SHORT)
				.show();
	}



	// RouteOverlay拖动过程中触发
		@Override
		public void onDrag(MapView arg0, RouteOverlay arg1, int arg2, GeoPoint arg3) {
			// TODO Auto-generated method stub
			
		}
		
		// RouteOverlay拖动开始时触发
		@Override
		public void onDragBegin(MapView arg0, RouteOverlay arg1, int arg2,
				GeoPoint arg3) {
			// TODO Auto-generated method stub
			
		}
		
		// RouteOverlay拖动完成触发
		@Override
		public void onDragEnd(MapView mapView, RouteOverlay overlay, int index,
				GeoPoint pos) {
			// TODO Auto-generated method stub
			
			try {
				startPoint = overlay.getStartPos();
				endPoint = overlay.getEndPos();
//				overlay.renewOverlay(mapView);
				searchRouteResult(startPoint, endPoint);
			} catch (IllegalArgumentException e) {
				ol.restoreOverlay(mMapView);
				overlayToBack(ol, mMapView);
			} catch (Exception e1) {
				overlay.restoreOverlay(mMapView);
				overlayToBack(ol, mMapView);
			}
		}
		
		private void overlayToBack(RouteOverlay overlay, MapView mapView) {
			startPoint = overlay.getStartPos();
			endPoint = overlay.getEndPos();
		}

		@Override
		public boolean onRouteEvent(MapView arg0, RouteOverlay arg1, int arg2,
				int arg3) {
			int maxstep = arg1.getRoute().getStepCount();
			if ((arg2 == 0 || maxstep == arg2) && arg3 == 4) {
				xiafa_dialog(arg1, arg2);
			}
			return false;
		}
		
		
		
		public void xiafa_dialog(final RouteOverlay arg1, final int arg) {
			// TODO 下发起点或是终点的对话框
			new AlertDialog.Builder(Drive.this)
					.setTitle("位置下发！")
					.setMessage("是否需要下发此点！")
					.setPositiveButton("下发", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dia, int which) {
							dia.dismiss();
							MypoiItems mypoiItems = new MypoiItems();
							Bundle bundle = new Bundle();
							Geocoder coder = new Geocoder(Drive.this);
							String addrss = "";
							String subaddr = "";
							if (arg == 0) {
								GeoPoint geoPoint = arg1.getStartPos();
								Route route = arg1.getRoute();

								try {
									List<Address> address = coder.getFromLocation(
											geoPoint.getLatitudeE6() / 1E6,
											geoPoint.getLongitudeE6() / 1E6, 3);
									if (address != null || address.size() > 0) {

										for (Address address2 : address) {
											if (address2.getPremises() == coder.Street_Road
													|| address2.getPremises() == coder.POI) {

												if (address2.getFeatureName() != null) {
													addrss += address2
															.getFeatureName();
												}
												if (address2.getLocality() != null) {
													subaddr += address2
															.getLocality();
												}
												if (address2.getSubLocality() != null) {
													subaddr += address2
															.getSubLocality();
												}
												subaddr += address2
														.getFeatureName();
											}
										}
										Log.i("mylog", addrss + "::" + subaddr);

										mypoiItems.setSnippet(subaddr);
										mypoiItems.setTitle(addrss);

									}
								} catch (AMapException e1) {
									Toast.makeText(getApplicationContext(),
											"数据获取失败,请检查网络连接！", Toast.LENGTH_SHORT)
											.show();
									e1.printStackTrace();
								}

								mypoiItems.setLatit(geoPoint.getLatitudeE6());
								mypoiItems.setLongit(geoPoint.getLongitudeE6());
								bundle.putParcelable("poi_xf", mypoiItems);
								Intent intent = new Intent(Drive.this,
										SendList.class);
								intent.putExtra("poi_xf", bundle);
								startActivity(intent);
							} else {
								GeoPoint geoPoint = arg1.getEndPos();
								Route route = arg1.getRoute();

								try {
									List<Address> address = coder.getFromLocation(
											geoPoint.getLatitudeE6() / 1E6,
											geoPoint.getLongitudeE6() / 1E6, 3);
									if (address != null || address.size() > 0) {

										for (Address address2 : address) {
											if (address2.getPremises() == coder.Street_Road
													|| address2.getPremises() == coder.POI) {

												if (address2.getFeatureName() != null) {
													addrss += address2
															.getFeatureName();
												}
												if (address2.getLocality() != null) {
													subaddr += address2
															.getLocality();
												}
												if (address2.getSubLocality() != null) {
													subaddr += address2
															.getSubLocality();
												}
												subaddr += address2
														.getFeatureName();
											}
										}
										Log.i("mylog", addrss + "::" + subaddr);

										mypoiItems.setSnippet(subaddr);
										mypoiItems.setTitle(addrss);

									}
								} catch (AMapException e1) {
									Toast.makeText(getApplicationContext(),
											"数据获取失败,请检查网络连接！", Toast.LENGTH_SHORT)
											.show();
									e1.printStackTrace();
								}

								mypoiItems.setLatit(geoPoint.getLatitudeE6());
								mypoiItems.setLongit(geoPoint.getLongitudeE6());
								bundle.putParcelable("poi_xf", mypoiItems);
								Intent intent = new Intent(Drive.this,
										SendList.class);
								intent.putExtra("poi_xf", bundle);
								startActivity(intent);
							}

						}
					})
					.setNegativeButton("不要", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dia, int which) {
							dia.dismiss();
							Log.i("mylog", "AlertDialog--->"
									+ Thread.currentThread().getId());
						}
					}).create().show();
		}
	
}
